﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gasco.Business.Services;
using Gasco.DataAccess;
using Mani.Common;

public partial class Controls_order_add : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadProducts();
            LoadOrderTypes();
            LoadPlattTypes();
            LoadCurrency();
            LoadBorders();
            LoadOrigins();
            LoadPriceCalculationType();
            LoadUnits();
            LoadContractTypes();

            if (Request.QueryString["id"] != null)
                LoadOrder();
            else
                tbPlattDate.Value = DateTime.Now.ToShortDateString();
        }
    }

    private void LoadContractTypes()
    {
        IOrderService os = new OrderService();
        ddContractType.DataSource = os.GetContractTypes();
        ddContractType.DataBind();
    }

    private void LoadUnits()
    {
        LookupService<unit> us = new LookupService<unit>();
        ddUnit.DataSource = us.GetAll();
        ddUnit.DataBind();
    }

    private void LoadPriceCalculationType()
    {
        LookupService<price_calculation_type> ps = new LookupService<price_calculation_type>();
        ddPriceCalculationType.DataSource = ps.GetAll();
        ddPriceCalculationType.DataBind();
    }

    private void LoadOrigins()
    {
        ProductService ps = new ProductService();
        ddOrigin.DataSource = ps.GetOrigins();
        ddOrigin.DataBind();
    }

    private void LoadBorders()
    {
        LookupService<border> bs = new LookupService<border>();
        ddBorder.DataSource = bs.GetAll();
        ddBorder.DataBind();
    }

    private void LoadProducts()
    {
        ProductService ps = new ProductService();
        ddProducts.DataSource = ps.GetProducts();
        ddProducts.DataBind();
    }

    private void LoadOrderTypes()
    {
        LookupService<order_type> ls = new LookupService<order_type>();
        ddOrderType.DataSource = ls.GetAll();
        ddOrderType.DataBind();
    }

    private void LoadPlattTypes()
    {
        LookupService<platts_type> ls = new LookupService<platts_type>();
        ddPlattType.DataSource = ls.GetAll();
        ddPlattType.DataBind();
    }

    private void LoadCurrency()
    {
        LookupService<currency> ls = new LookupService<currency>();
        ddCurrency.DataSource = ls.GetAll();
        ddCurrency.DataBind();
    }

    private void LoadOrder()
    {
        int id = Convert.ToInt32(Request.QueryString["id"]);
        IOrderService os = new OrderService();
        IContactService cs = new ContactService();
        IProductService ps = new ProductService();
        IPlattService plattService = new PlattService();
        LookupService<currency> currencyService = new LookupService<currency>();
        LookupService<unit> unitService = new LookupService<unit>();

        order o = os.GetOrderById(id);
        platt p = plattService.GetByProductAndDate(o.product_id, o.create_date.Value, o.platt_type_id);
        if (p == null)
        {
            UIHelper.ClientAlert( GetLocalResourceObject("PlattsNotFoundError") +  o.create_date.ToJalali() );
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script1", "<script>pageClose();</script>");
            return;
        }

        ddProducts.SelectedValue = o.product_id.ToString();
        ddOrderType.SelectedValue = o.order_type.ToString();
        ddPlattType.SelectedValue = o.platt_type_id.ToString();
        ddCurrency.SelectedValue = o.currency_id.ToString();
        ddBorder.SelectedValue = o.border_id.ToString();
        ddOrigin.SelectedValue = o.origin_id.ToString();
        ddContractType.SelectedValue = o.contract_type_id.ToString();

        tbOrderNumber.Text = o.order_number.ToString();
        tbOrderName.Text = o.order_name.ToString();

        tbSeller.Text = (o.seller_id != 0 ? cs.GetContactById(o.seller_id.Value).name : "");
        tbBuyer.Text = (o.buyer_id != 0 ? cs.GetContactById(o.buyer_id.Value).name : "");
        tbBroker.Text = (o.broker_id != 0 ? cs.GetContactById(o.broker_id.Value).name : "");
        tbTransporter.Text = (o.transporter_id != 0 ? cs.GetContactById(o.transporter_id.Value).name : "");
        ddPriceCalculationType.SelectedValue = o.price_calculation_type_id.ToString();

        if (o.price_calculation_type_id == (int)PriceCalculationType.Fixed)
        {
            tbFormula.Text = o.formula;
            tbPlatt.Text = UIHelper.FormatString(plattService.GetById(o.platts_id.Value).price);            
            tbPlattDate.Value = o.create_date.Value.ToShortDateString();

            tbPrice.Text = UIHelper.FormatString(o.price);
            string currencyVal = currencyService.FindById(p.currency_id).name;
            lbPlattCurrency.Text = currencyVal;
            lbPriceCurrency.Text = currencyVal;
        }

        tbQuantity.Text = o.quantity.ToString();
        ddUnit.SelectedValue = o.unit_id.ToString();

        if (o.purchase_order.HasValue)
        {
            order purchaseOrder = os.GetOrderById(o.purchase_order.Value);
            if (purchaseOrder != null)
            {
                tbPurchaseOrderName.Text = purchaseOrder.order_name;
                tbPurchaseOrderNumber.Text = purchaseOrder.order_number;
            }
        }

        tbStartDate.Text = o.start_date.ToJalali();
        tbExpireDate.Text = o.expire_date.ToJalali();
    }

    protected void btnclose_Click(object sender, EventArgs e)
    {
        SaveOrder();
    }

    private void SaveOrder()
    {
        ContactService cs = new ContactService();
        OrderService os = new OrderService();
        IPlattService plattService = new PlattService();
        order o = null;
        int id = 0;

        if (Request.QueryString["id"] == null)
        {
            o = new order();
            o.create_date = DateTime.Now;
        }
        else
        {
            id = Convert.ToInt32(Request.QueryString["id"]);
            o = os.GetOrderById(id);
        }

        o.product_id = Convert.ToInt32(ddProducts.SelectedValue);
        o.origin_id = Convert.ToInt32(ddOrigin.SelectedValue);
        o.order_type = Convert.ToInt32(ddOrderType.SelectedValue);
        o.order_number = tbOrderNumber.Text;
        o.order_name = tbOrderName.Text;
        o.price_calculation_type_id = Convert.ToInt32(ddPriceCalculationType.SelectedValue);
        o.platt_type_id = Convert.ToInt32(ddPlattType.SelectedValue);
        o.contract_type_id = Convert.ToInt32(ddContractType.SelectedValue);

        if (o.price_calculation_type_id == (int)PriceCalculationType.Fixed)
        {
            o.formula = tbFormula.Text;
            if (String.IsNullOrEmpty(tbPlatt.Text))
                o.platts_id = null;
            else
            {
                platt p = plattService.GetByProductAndDate(o.product_id, o.create_date.Value, o.platt_type_id);
                if (p == null)
                    o.platts_id = null;
                else
                    o.platts_id = p.id;
            }
            o.price = Convert.ToSingle(UIHelper.RemoveFormat( tbPrice.Text ));
        }
        else
        {
            o.platts_id = null;
            o.formula = null;
            o.price = null;
        }

        if ( ddBorder.SelectedValue != "-1" )
            o.border_id = Convert.ToInt32(ddBorder.SelectedValue);
        
        o.quantity = Convert.ToSingle(tbQuantity.Text);
        o.unit_id = Convert.ToInt32(ddUnit.SelectedValue);
        o.currency_id = Convert.ToInt32(ddCurrency.SelectedValue);
        o.start_date = tbStartDate.Text.ToDateTime();
        o.expire_date = tbExpireDate.Text.ToDateTime();
        o.update_date = DateTime.Now;

        try
        {
            o.seller_id = cs.GetContactIdByName(tbSeller.Text);
            o.buyer_id = cs.GetContactIdByName(tbBuyer.Text);
            o.broker_id = cs.GetContactIdByName(tbBroker.Text);
            o.transporter_id = cs.GetContactIdByName(tbTransporter.Text);
        }
        catch (ContactNameNotFoundException ex)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("ContactNameNotFoundException") + ex.ContactName);
            return;
        }

        if (String.IsNullOrEmpty(tbPurchaseOrderNumber.Text))
        {
            o.purchase_order = null;
        }
        else
        {
            order purchaseOrder = null;
            try
            {
                purchaseOrder = os.GetOrderByNumber(tbPurchaseOrderNumber.Text);
            }
            catch (OrderNumberNotFoundException)
            {
                UIHelper.ClientAlert(this.Page, GetLocalResourceObject("OrderNumberNotFoundException").ToString() + tbPurchaseOrderNumber.Text);
                return;
            }

            if (purchaseOrder != null)
                o.purchase_order = purchaseOrder.id;
        }

        try
        {
            if (Request.QueryString["id"] == null)
                os.CreateOrder(o);
            else
                os.UpdateOrder(o);

            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script1", "<script>pageClose();</script>");
        }
        catch (InvalidQuantityException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("InvalidQuantityException").ToString());
        }
        catch (PurchaseOrderNotSpecifiedException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("PurchaseOrderNotSpecifiedException").ToString());
        }
        catch (PurchaseOrderNotFoundException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("PurchaseOrderNotFoundException").ToString());
        }
        catch (PurchaseOrderMustBeNullException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("PurchaseOrderMustBeNullException").ToString());
        }
        catch (ExpireAndCreateDateMismatch)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("ExpireAndCreateDateMismatch").ToString());
        }
        catch (BorderRequiredForSaleException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("BorderRequiredForSaleException").ToString());
        }
        catch (PurchaseAndSaleExpireDateMismatch)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("PurchaseAndSaleExpireDateMismatch").ToString());
        }
        catch (DuplicateOrderException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("DuplicateOrderException").ToString());
        }
        catch (OrderNumberNotFoundException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("OrderNumberNotFoundException").ToString() + tbPurchaseOrderNumber.Text);
        }
    }
}